import time

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from datetime import datetime
from selenium.webdriver.support import expected_conditions as e
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
class Base():
    def __init__(self,driver):
        self.driver=driver



    def open_url(self,url):
        self.driver.get(url)



    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:driver.find_element(*loc).is_displayed())

            return self.driver.find_element(*loc)

        except Exception as e:
            #获取时间戳
            datatime=datetime.now().strftime('%Y%m%d %H%M%S')
            #截图
            self.driver.save_screenshot(f'error_{datatime}.png')
            print('未定位到元素',e)


    #输入方法
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    #点击方法
    def click(self,loc):
        self.find_element(loc).click()


    #切换页面
    def window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    #滚动条
    def execute_script(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    #弹框处理
    def alert(self):
        day1=self.driver.switch_to.alert
        #确认
        day1.accept()

    def alert1(self):
        day1=self.driver.switch_to.alert
        #取消
        day1.dismiss()

    #iframe处理
    def iframe(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
    #鼠标事件，
    def key(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)
    #键盘事件
    def action_chains(self,loc):
        ActionChains(self.driver).double_click(self.find_element(loc)).perform()
    #浏览器事件
    def refresh(self):
        self.driver.refresh()
    #下拉框选择
    def select(self,loc,x):
        day=Select(self.find_element(loc))
        day.select_by_value(x)
    #下拉框选择
    def select2(self, loc, x):
        day = Select(self.find_element(loc))
        day.select_by_index(x)
    #下拉框选择
    def select3(self, loc, x):
        day = Select(self.find_element(loc))
        day.select_by_visible_text(x)

    #强制等待时间
    def sellp(self,x):
        time.sleep(x)

    #隐式等待时间
    def implicitly_wait(self,x):
        self.driver.implicitly_wait(x)


    #隐式等待
    def WebDriverWait(self,loc):
        WebDriverWait(self.driver,20,0.5).until(e.presence_of_element_located(loc))


